/*
 * Copyright (C) 2024, Ingenic Semiconductor Co.,Ltd.
 * Author: Keven <keven.ywhan@ingenic.com>
 */

#include <config.h>
#include <base.h>

#define RESERVED_FOR_SC(x) .space 1536, x

.globl _start
_start:
#ifdef CONFIG_SPL_MMC_SUPPORT
	/* magic value ("MSPL") */
	.word 0x4d53504c
	.space 508, 0
	RESERVED_FOR_SC(0)
#elif CONFIG_SPL_SFC_SUPPORT
	.word 0x03040506
	.word 0x55aa5502
#ifdef CONFIG_SPL_SFC_NOR
	.word 0x000000aa
#elif CONFIG_SPL_SFC_NAND
#define SSI_PPB	(CONFIG_SPI_NAND_PPB / 32)
#define SSI_BPP (CONFIG_SPI_NAND_BPP / 1024)
	.word (0x00000000 | (SSI_PPB<<16) | (SSI_BPP<<24))
#endif
	.space 500, 0
	RESERVED_FOR_SC(0)
#endif

	/* clear mie and mip */
	li 	t0, 0
	csrw	mie, t0
	csrw	mip, t0

	/* set all registers to zero */
	mv	x1, x0
	mv  	x2, x1
	mv  	x3, x1
	mv  	x4, x1
	mv  	x5, x1
	mv  	x6, x1
	mv  	x7, x1
	mv  	x8, x1
	mv  	x9, x1
	mv	x10, x1
	mv	x11, x1
	mv 	x12, x1
	mv 	x13, x1
	mv 	x14, x1
	mv 	x15, x1
	mv 	x16, x1
	mv 	x17, x1
	mv 	x18, x1
	mv 	x19, x1
	mv 	x20, x1
	mv 	x21, x1
	mv 	x22, x1
	mv 	x23, x1
	mv 	x24, x1
	mv 	x25, x1
	mv 	x26, x1
	mv 	x27, x1
	mv 	x28, x1
	mv 	x29, x1
	mv 	x30, x1
	mv 	x31, x1

.option push
.option norelax
	la	gp, __global_pointer$	/* temporary address */
.option pop

	/*Set trap_entry*/
	la	t0, trap_entry
	csrw	mtvec, t0

  	/* clear BSS */
clear_bss:
	la	t0, __bss_start
	la	t1, __bss_end
	bge	t0, t1, zero_loop_end

zero_loop:
	sw	x0, 0(t0)
	addi	t0, t0, 4
	ble	t0, t1, zero_loop
zero_loop_end:

	/* stack initilization */
	la	sp, __sp
	call	spl_main

.align 4
trap_entry:
	call	handle_trap

.globl main_hart_deal_start
.globl main_hart_deal
main_hart_deal_start:
main_hart_deal:
	li	t3, (CCU_BASE + CCU_MSCR)
	lw	t5, 0(t3)
	lui	t4, 0xffffe
	addi	t4, t4, 1023
	and	t5, t5, t4
	lui	t4, 0x2
	slli	a0, a0, 0xa
	addi	t4, t4, -1024
	and	a0, a0, t4
	or	a0, a0, t5
	sw	a0, 0(t3)
	/* start_harts */
	li	a5, (CCU_BASE + CCU_CSRR)
	lw	a4, 0(a5)
	not	a1, a1
	and	a1, a1, a4
	sw	a1, 0(a5)
	jr	a2
.globl main_hart_deal_end
main_hart_deal_end:
